import { Byte } from '../../api/io/Byte';
import { ITimer } from '../../api/timer/ITimer';
import { IAsync } from '../../api/event/IAsync';



/**竞技场属性枚举*/
export const enum E_ArenaSnapshot {
	/**参与竞技*/
	JOIN = 0,
	/**排名*/
	RANK_INDEX = 1,
	/**枚举数量*/
	EnumCount = 2
}


/**竞技场*/
export class ArenaSnapshot {
	/**事件ID*/
	public static readonly EVENT_ID = 'STRUCT_DATA_ARENA_SNAPSHOT_EVENT_ID';
	/**整体更新事件ID（部分只需要监听整体变化）*/
	public static readonly TOTAL_EVENT_ID = 'STRUCT_DATA_ARENA_SNAPSHOT_TOTAL_EVENT_ID';
	/**缓存池*/
	private static POOL: ArenaSnapshot[] = [];

	/**创建入口*/
	public static create(json?: string): ArenaSnapshot {
		const c = this.POOL.pop() || new ArenaSnapshot();
		c._destroyed = false;
		c.resetProperty();
		if (json) {
			c.parse(json);
		}
		return c;
	}


	/**已释放*/
	protected _destroyed = false;
	/**参与竞技*/
	protected _join: boolean;
	/**排名 (int32)*/
	protected _rankIndex: number;


	/**构建函数-私有，防止外部创建*/
	private constructor() {
	}


	/**释放*/
	public destroy(): void {
		if (this._destroyed) {
			return;
		}
		this._destroyed = true;
		this.resetProperty(true);
		if (ArenaSnapshot.POOL.indexOf(this) === -1) {
			ArenaSnapshot.POOL.push(this);
		}
	}

	/**参与竞技*/
	public get join() {
		return this._join;
	}


	/**参与竞技*/
	public set join(v: boolean) {
		this._join = v;
	}


	/**排名*/
	public get rankIndex() {
		return this._rankIndex;
	}


	/**排名*/
	public set rankIndex(v: number) {
		this._rankIndex = v;
	}



	/**通过枚举获取值*/
	public getV(k: E_ArenaSnapshot): any {
		switch (k) {
			case E_ArenaSnapshot.JOIN: return this._join;
			case E_ArenaSnapshot.RANK_INDEX: return this._rankIndex;
			default: return null;
		}
	}


	/**通过枚举设置值*/
	public setV(k: E_ArenaSnapshot, v: any): void {
		switch (k) {
			case E_ArenaSnapshot.JOIN: this._join = v; break;
			case E_ArenaSnapshot.RANK_INDEX: this._rankIndex = v; break;
			default: break;
		}
	}


	/**初始化*/
	public resetProperty(fromDestroy = false): void {
		//参与竞技
		this._join = false;
		//排名
		this._rankIndex = 0;
	}


	/**序列化*/
	public stringify(toString: boolean): string | any {
		const json: any = {};
		if (this._join) {
			json.join = this._join;
		}
		if (this._rankIndex) {
			json.rankIndex = this._rankIndex;
		}

		return toString ? JSON.stringify(json) : json;
	}


	/**反序列化*/
	public parse(jsonv: string | any): this {
		this.resetProperty();
		if (!jsonv) {
			return this;
		}
		const json = typeof (jsonv) === 'string' ? JSON.parse(jsonv) : jsonv;
		if (json.join) {
			this._join = json.join;
		}
		if (json.rankIndex) {
			this._rankIndex = json.rankIndex;
		}
		return this;
	}


	/**序列化-二进制*/
	public toBytes(byte: Byte): void {
		if (!byte) {
			return;
		}
		byte.writeBool(this._join);
		byte.writeInt32(this._rankIndex);
	}


	/**反序列化-二进制*/
	public fromBytes(byte: Byte): this {
		this.resetProperty();
		if (!byte) {
			return;
		}
		this._join = byte.readBool();
		this._rankIndex = byte.readInt32();
		return this;
	}


	/**克隆*/
	public clone(): ArenaSnapshot {
		const byte = Byte.createFromPool();
		this.toBytes(byte);
		byte.pos = 0;
		const clonev = ArenaSnapshot.create().fromBytes(byte);
		Byte.recoverToPool(byte);
		return clonev;
	}


	/**处理更新*/
	public processUpdate(jsonv: string): void {
		if (!jsonv) {
			return;
		}

		const eventID = ArenaSnapshot.EVENT_ID;
		const us = JSON.parse(jsonv);

		for (let i = 0, len = us.length; i < len;) {
			const idx = us[i];
			//参与竞技
			if (idx === E_ArenaSnapshot.JOIN) {
				const oldv = this._join;
				this._join = us[i + 1];
				IAsync.dispatch(eventID, idx, this._join, oldv);
				i += 2;
				continue;
			}
			//排名
			if (idx === E_ArenaSnapshot.RANK_INDEX) {
				const oldv = this._rankIndex;
				this._rankIndex = us[i + 1];
				IAsync.dispatch(eventID, idx, this._rankIndex, oldv);
				i += 2;
				continue;
			}

			console.error('[Struct Data] can not find enum in ArenaSnapshot with idx = ' + idx + ', version maybe wrong.')
		}

		//全更事件
		ITimer.callLater(this, this.dispatchTotalUpdate);
	}


	/**比对不一致结果*/
	public getCompareInfo(other: ArenaSnapshot): string {
		if (!other) {
			return null;
		}

		const updates: any[] = [];

		if (this._join !== other._join) {
			updates.push(E_ArenaSnapshot.JOIN, this._join);
		}
		if (this._rankIndex !== other._rankIndex) {
			updates.push(E_ArenaSnapshot.RANK_INDEX, this._rankIndex);
		}

		const jsonv = updates.length === 0 ? null : JSON.stringify(updates);
		return jsonv;
	}


	/**全部更新*/
	protected dispatchTotalUpdate(): void {
		IAsync.dispatch(ArenaSnapshot.TOTAL_EVENT_ID, this.getV(0));
	}

}
